import { cloneDeep } from 'lodash-es'
import { STORAGE_MODES } from '@/enum/modules/indicator'
import type {
  IndicatorSubmitInfoParams,
  IndicatorSubmitInfoResult,
  IndicatorSubmitSubmitParams,
} from '@/types'
import { indicatorSubmitApi } from '@/api'

export interface EntryDataItem {
  time: string
  value: number
}

function splitTimeWithTimeType(
  timeType: STORAGE_MODES,
  time: string,
): string[] {
  const result: string[] = []
  if (timeType === STORAGE_MODES.FIFTEEN_MINUTES) {
    let h = 0
    let m = 0
    const n = 15
    const length = (24 * 60) / 15
    for (let i = 0; i < length; i++) {
      m += n
      h = Math.floor(m / 60)
      result.push(
        `
          ${h.toString().padStart(2, '0')}:${(m % 60)
          .toString()
          .padStart(2, '0')}
        `,
      )
    }
  }
  else if (timeType === STORAGE_MODES.HOUR) {
    let h = 0
    const length = 24
    for (let i = 0; i < length; i++) {
      h += 1
      result.push(`${h.toString().padStart(2, '0')}:00`)
    }
  }
  else if (timeType === STORAGE_MODES.DAY) {
    const date = new Date(time)
    date.setMonth(date.getMonth() + 1)
    date.setDate(0)
    const length = date.getDate()
    for (let i = 0; i < length; i++) {
      result.push(
        `${time}-${(i + 1).toString().padStart(2, '0')}`,
      )
    }
  }
  else if (timeType === STORAGE_MODES.MONTH) {
    for (let i = 0; i < 12; i++) {
      result.push(
        `${time}-${(i + 1).toString().padStart(2, '0')}`,
      )
    }
  }
  else if (timeType === STORAGE_MODES.YEAR) {
    const [start, end] = time.split(',')
    let i = Number(start)
    const length = Number(end)
    if (i && length) {
      for (; i <= length; i++) {
        result.push(`${i}`)
      }
    }
  }
  return result
}

async function getLists(params: {
  indicatorId: number
  time: string
  timeType: STORAGE_MODES
}) {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve(
        splitTimeWithTimeType(
          params.timeType,
          params.time,
        ).map(v => ({
          time: v,
          // value: +(Math.random() * 1000).toFixed(2)
          value: null,
        })),
      )
    }, 400)
  })
}

/** 指标数据录入 */
export function useEntryData(needLoading: boolean = true) {
  const [loading, setLoading] = useState(false)
  const [lists, setLists] = useState<
    IndicatorSubmitInfoResult['dataList']
  >([])
  const [saving, setSaving] = useState(false)

  async function getEntryDataByIndicatorId(
    params: IndicatorSubmitInfoParams,
  ) {
    setLists([])
    needLoading && setLoading(true)
    try {
      const { data: res } = await indicatorSubmitApi.info(
        params,
      )
      setLists(res.dataList)
    }
    catch (e) {
    }
    finally {
      needLoading && setLoading(false)
    }
  }

  async function saveOrUpdateEntryData(
    data: IndicatorSubmitSubmitParams,
  ) {
    setSaving(true)
    try {
      const params = cloneDeep(data)
      params.dataList = params.dataList.filter(
        item => item.val !== null,
      )
      // if (params.dataList.length === 0) {
      //   ElMessage.warning('请填写指标数据!');
      //   return;
      // }

      await indicatorSubmitApi.submit(params)
      ElMessage.success('保存成功')
    }
    catch (e) {
    }
    finally {
      setSaving(false)
    }
  }

  return {
    /** 指标录入的数据 */
    lists,
    setLists,

    loading,
    setLoading,

    /** 保存中的状态 */
    saving,
    setSaving,

    /** 查询某个数据存储为录入的指标所录入的数据 */
    getEntryDataByIndicatorId,
    /** 保存或更新某个数据存储为录入的指标所录入的数据 */
    saveOrUpdateEntryData,
  }
}
